<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理员主页</title>
    <script>
        //路由守卫
        const token=localStorage.getItem("token")
        if(token){

        }else{
            alert("请先登录")
            window.location.href=`../login.html`
        }
    </script>
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            display: flex;
        }
        
        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background-color: #333;
            color: white;
            height: 100vh;
            padding: 20px 0;
            box-sizing: border-box;
            transition: width 0.3s;
        }
        .sidebar-header {
            padding: 0 20px 20px;
            text-align: center;
        }
        
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .sidebar-menu li {
            padding: 15px 20px;
            transition: background-color 0.3s;
        }
        
        .sidebar-menu li:hover {
            background-color: #555;
            cursor: pointer;
        }
        
        .sidebar-menu li.active {
            background-color: #007bff;
        }
        
        .sidebar-menu a {
            color: white;
            text-decoration: none;
            display: flex;
            align-items: center;
        }
        
        .sidebar-menu i {
            margin-right: 10px;
        }
        
        /* 主内容区域 */
        .main-content {
            flex: 1;
            padding: 20px;
        }

        /* 新闻管理区域 */
        * {
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }

        .news {
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        h1 {
            margin-top: 0;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background-color: #4285f4;
            color: white;
        }
        .logout{
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            background-color: #4285f4;
            color: white;
        }
        .logout:hover{
            background-color: #3367d6;
        }
        .btn-primary:hover {
            background-color: #3367d6;
        }

        .btn-danger {
            background-color: #ea4335;
            color: white;
        }

        .btn-danger:hover {
            background-color: #d33426;
        }

        .search-box {
            display: flex;
            align-items: center;
        }

        .search-box input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            width: 250px;
        }

        .search-box button {
            padding: 8px 12px;
            background-color: #f1f1f1;
            border: 1px solid #ddd;
            border-left: none;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f9f9f9;
            font-weight: bold;
            color: #555;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        .status-published {
            color: #34a853;
            font-weight: bold;
        }

        .status-draft {
            color: #fbbc05;
            font-weight: bold;
        }

        .action-buttons button {
            margin-right: 5px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination button {
            margin: 0 5px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
        }

        .pagination button.active {
            background-color: #4285f4;
            color: white;
            border-color: #4285f4;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-style: italic;
            color: #888;
        }

        /* 编辑框样式 *//* 按钮样式 */
        .edit-btn {
            padding: 8px 16px;
            background: #409eff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        /* 遮罩层：半透明背景 */
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
            display: none; /* 默认隐藏 */
        }
        
        /* 编辑框容器：居中显示 */
        .edit-modal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 500px;
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            z-index: 1000;
            display: none; /* 默认隐藏 */
        }
        
        /* 编辑框标题 */
        .modal-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #333;
        }
        /* 输入框样式 */
        .edit-input {
            width: 100%;
            padding: 10px;
            margin-bottom: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-size: 14px;
            resize: vertical; /* 只允许垂直拉伸 */
        }
        .btn-group {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .cancel-btn, .confirm-btn {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            border: 1px solid #ddd;
        }
        
        .confirm-btn {
            background: #409eff;
            color: #fff;
            border-color: #409eff;
        }


         /* 页面标题 */
         .page-title {
            font-size: 22px;
            color: #333;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        /* 操作按钮样式 */
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #409eff;
            color: #fff;
        }

        .btn-danger {
            background-color: #f56c6c;
            color: #fff;
        }

        .btn:hover {
            opacity: 0.9;
        }

        /* 搜索与筛选区 */
        .search-bar {
            background-color: #fff;
            padding: 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            align-items: center;
        }

        .search-input {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }


        .filter-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: #fff;
        }

        /* 资源列表表格 */
        .resource-table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        }

        .resource-table th,
        .resource-table td {
            padding: 14px 16px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 14px;
        }

        .resource-table th {
            background-color: #fafafa;
            color: #666;
            font-weight: 500;
        }

        .resource-table tbody tr:hover {
            background-color: #f9fafc;
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h2>网站管理</h2>
        </div>
        <button id="closeButton">^</button>
        <ul class="sidebar-menu">
            <li class="active" id="newsManagement">
                <a href="#">
                    <span>新闻管理</span>
                </a>
            </li>
            <li id="resourceManagement">
                <a href="#">
                    <span>资源管理</span>
                </a>
            </li>
            <li id="userManagement">
                <a href="#">
                    <span>用户管理</span>
                </a>
            </li>
            <li id="dashboardShow">
                <a href="#">
                    <span>仪表盘</span>
                </a>
            </li>
        </ul>
    </div>
    <!-- 主内容区域 -->
    <div class="main-content" >
        <div id="news">
            <div class="container">
                <h1>新闻管理</h1>
                <div class="toolbar">
                    <div>
                        <button class="btn btn-primary" id="addNewsBtn" onclick="openModal()">添加新闻</button>
                    </div>
                    <div class="search-box">

                        <input type="text" id="searchInput" placeholder="搜索新闻标题...">
                        <button id="searchBtn">搜索</button>
                    </div>
                </div>

                <div class="tableContainer">
                    <table id="newsTable">
                        <thead>
                        <tr>
                            <th>序号</th>
                            <th>标题</th>
                            <th>分类</th>
                            <th>作者</th>
                            <th>发布时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="newsTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                        <tr>
                            <td colspan="7" class="loading">正在加载数据...</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="pagination" id="pagination">
                    <!-- 分页将通过JavaScript动态生成 -->
                </div>
            </div>
            </div>

            <!-- 
            <div id="users">
                <span>users666</span>
            </div>
            <div id="dashboard">
                <span>dashboard666</span>
            </div> -->
            <!-- 触发按钮 -->
            
            <!-- 遮罩层 -->
            <div class="mask" onclick="closeModal()"></div>
            
            <!-- 编辑框 -->
            <div class="edit-modal">
                <div class="modal-title">编辑信息</div>
                <!-- 编辑输入框 -->
                <label for="editTitle">标题</label>
                <input type="text" class="edit-input" id="editTitle" placeholder="请输入新闻标题"/>
                <label for="editContent">内容</label>
                <textarea class="edit-input" id="editContent" placeholder="请输入新闻内容"></textarea>
                <label for="editAuthor">作者</label>
                <input type="text" class="edit-input" id="editAuthor" placeholder="请输入作者"/>
                <label for="editCategory">分类</label>
                <select class="edit-input" id="editCategory">
                    <option value="通知公告">通知公告</option>
                    <option value="项目新闻" selected>项目新闻</option>
                    <option value="媒体报道">媒体报道</option>
                </select>
                <label for="editImage">配图</label>
                <input type="file" class="edit-input" id="editImage" placeholder="请上传图片文件"/>
                <!-- 操作按钮 -->
                <div class="btn-group">
                    <button class="cancel-btn" onclick="closeModal()">取消</button>
                    <button class="confirm-btn" onclick="saveEdit()">确认保存</button>
                </div>
            </div>
            
            <!-- 资源管理区域 --> 
            <div id="resources">
                <div class="container">
                    <h1>资源管理</h1>
                    <div class="toolbar">
                        <div>
                            <button class="btn btn-primary" id="addResourceBtn">上传文件</button>
                            <input type="file" id="file-upload" style="display:none;"/>
                        </div>
                        <div class="search-box">
                            <input type="text" id="searchInput1" placeholder="搜索对应资源">
                            <button id="searchBtn1">搜索</button>
                        </div>
                    </div>
                    <div class="tableContainer">
                        <table id="resourceTable">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th>文件</th>
                                <th>分类</th>
                                <th>上传者</th>
                                <th>上传时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="resourceTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                            <tr>
                                <td colspan="6" class="loading"></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="pagination" id="pagination1">
                        <!-- 分页将通过JavaScript动态生成 -->
                    </div>
                </div>
</div>
</div>
<button class="logout">退出登录</button>
</div>


<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script >
    //添加折叠功能
    $(()=>{
        let content="newsManagement";
        let isCollapsed = false;
        $('.main-content > div').hide();
        $('#news').show();
        $('#newsManagement').addClass('active');
        $('#closeButton').text('<');
        $('#closeButton').on('click', function() {
            if (isCollapsed) {
                $('.sidebar').css('width', '250px');
                $('.sidebar-menu').show();
                $('.sidebar-header h2').show();
                $('#closeButton').text('<');
            } else {
                $('.sidebar').css('width', '70px');
                $('.sidebar-menu').hide();
                $('.sidebar-header h2').hide();
                $('#closeButton').text('>');
            }
            isCollapsed = !isCollapsed;
        });

        // 为每个菜单项添加点击事件
        $('.sidebar-menu li').on('click', function() {
            $('.sidebar-menu li').removeClass('active');
            $(this).addClass('active');
            content = $(this).attr('id');
            console.log(content);
            $('.main-content > div').hide();
            if(content==="newsManagement"){
                $('#news').show();
            }else if(content==="resourceManagement"){
                fetchResourceData();
                $('#resources').show();
            }else if(content==="userManagement"){
                $('#users').show();
            }else if(content==="dashboardShow"){
                $('#dashboard').show();
            }
        });
        //退出登录事件
        $('.logout').on('click', function() {
            localStorage.clear();
            window.location.href="../login.html";
        })


        $('#addResourceBtn').on('click',function(){
            $('#file-upload').click();});
    // 页面加载完成后初始化Token拦截器
    $(document).on('ajaxSend', function(event, jqxhr, settings) {

        const token = localStorage.getItem('token');
        if (token) {
            jqxhr.setRequestHeader('Authorization', `${token}`);
        }else{
            jqxhr.abort();
            alert("请先登录");
            window.location.href = "../login.html";
        }

    })
    fetchNewsData();
    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') handleSearch();
        });

    fetchResourceData();
        $("#searchBtn1").on('click',handleSearch1);
        $(searchInput1).on('keypress',function(e){
            if(e.key==='Enter') handleSearch1();
        });
    
});

    

    // 全局变量（news）
    let currentPage = 1;
    const pageSize = 10;
    let totalNews = 0;
    let newsData = [];
    let filteredData = [];
    // 全局变量
    let currentPage1 = 1;
    let totalResource = 0;
    let resourceData = [];
    let filteredData1 = [];
    
    // DOM元素
    const tableBody = document.getElementById('newsTableBody');
    const paginationEl = document.getElementById('pagination');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const addNewsBtn = document.getElementById('addNewsBtn');
    // 从后端获取新闻数据
    async function fetchNewsData() {
        try {
            // 模拟API请求 - 实际项目中替换为真实的API调用
                $.ajax(
                    {
                        type: "GET",
                        url: "/news",
                        success: function(response) {
                            if(response.code===200){
                                console.log(response);
                                const data=response.data;
                                newsData=data;
                                filteredData=[...data];
                                totalNews=data.length;
                                renderTable();
                                renderPagination();
                            }else{
                                alert("获取新闻数据失败");
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('获取新闻数据失败:', error);
                            if (xhr.status===403) {
                                alert("权限不足")
                                window.location.href = "../home.html";
                            }
                        }
                    }
                )
        } catch (error) {
            console.error('获取新闻数据失败:', error);
            tableBody.innerHTML = '<tr><td colspan="7">数据加载失败，请稍后重试</td></tr>';
        }
    }

    // 从后端获取资源数据
    async function fetchResourceData(){
        try{
            // 模拟API请求 - 实际项目中替换为真实的API调用

                
            $.ajax(
                {
                    type: "GET",
                    url: "/resources",
                    success: function(response) {
                        if(response.code===200){
                            console.log(response);
                            const data=response.data;
                            resourceData=data;
                            filteredData1=[...data];
                            totalResource=data.length;
                            renderTable1();
                            renderPagination1();
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('获取资源数据失败:', error);
                        if (xhr.status===403) {
                            alert("权限不足")
                            window.location.href = "../home.html";
                        }
                    }
                }
            )

            renderTable1();
            renderPagination1();
        }catch(error){
            console.error('获取资源数据失败:', error);
            tableBody1.innerHTML = '<tr><td colspan="6">数据加载失败，请稍后重试</td></tr>';}
    }
    // 渲染表格数据
    function renderTable() {
        if (filteredData.length === 0) {
            tableBody.innerHTML = '<tr><td colspan=""></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
            return;
        }

        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, filteredData.length);
        const currentPageData = filteredData.slice(startIndex, endIndex);

        let html = '';

        currentPageData.forEach((news,index) => {
            html += `
                    <tr>
                        <td>${index+1}</td>
                        <td>${news.title}</td>
                        <td>${news.category}</td>
                        <td>${news.author}</td>
                        <td>${formatDate(news.publishTime)}</td>
                        <td><span class="status-${news.status}">已发布</span></td>
                        <td class="action-buttons">
                            <button class="btn btn-primary" onclick="editNews(${news.newsId})">编辑</button>
                            <button class="btn btn-danger" onclick="deleteNews(${news.newsId})">删除</button>
                        </td>
                    </tr>
                `;
        });
        tableBody.innerHTML = html;
    }
    function renderTable1(){
        if (filteredData.length === 0) {
            return;
        }

        const startIndex = (currentPage1 - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, filteredData1.length);
        const currentPageData = filteredData1.slice(startIndex, endIndex);

        let html = '';

        currentPageData.forEach((resource, index, array) => {
            html += `
                    <tr>
                        <td>${index+1}</td>
                        <td>${resource.fileName}</td>
                        <td>${resource.type}</td>
                        <td>${resource.uploader}</td>
                        <td>${formatDate(resource.uploadTime)}</td>
                        <td class="action-buttons">
                            <button class="btn btn-danger" onclick="deleteResource(${resource.resourceId})">删除</button>
                        </td>
                    </tr>
                `;
        });
        $('#resourceTableBody').html(html);

    }
    // 渲染分页
    function renderPagination() {
        const totalPages = Math.ceil(filteredData.length / pageSize);

        if (totalPages <= 1) {
            paginationEl.innerHTML = '';
            return;
        }

        let html = '';

        // 上一页按钮
        html += `<button onclick="goToPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>`;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            html += `<button onclick="goToPage(${i})" ${i === currentPage ? 'class="active"' : ''}>${i}</button>`;
        }

        // 下一页按钮
        html += `<button onclick="goToPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>下一页</button>`;

        paginationEl.innerHTML = html;
    }
    function renderPagination1(){
        const totalPages = Math.ceil(filteredData1.length / pageSize);

        if (totalPages <= 1) {
            $('#pagination1').html('');
            return;
        }

        let html = '';

        // 上一页按钮
        html += `<button onclick="goToPage1(${currentPage1 - 1})" ${currentPage1 === 1 ? 'disabled' : ''}>上一页</button>`;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            html += `<button onclick="goToPage1(${i})" ${i === currentPage1 ? 'class="active"' : ''}>${i}</button>`;
        }

        // 下一页按钮
        html += `<button onclick="goToPage1(${currentPage1 + 1})" ${currentPage1 === totalPages ? 'disabled' : ''}>下一页</button>`;

        $('#pagination1').html(html);
    }
    // 分页导航
    function goToPage(page) {
        if (page < 1 || page > Math.ceil(filteredData.length / pageSize)) return;
        currentPage = page;
        renderTable();
        renderPagination();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    function goToPage1(page){
        if (page < 1 || page > Math.ceil(filteredData1.length / pageSize)) return;
        currentPage1 = page;
        renderTable1();
        renderPagination1();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    // 搜索处理
    function handleSearch() {
        const keyword = searchInput.value.trim().toLowerCase();

        if (keyword === '') {
            filteredData = [...newsData];
        } else {
                filteredData = newsData.filter(news =>
                news.title.toLowerCase().includes(keyword) ||
                news.category.toLowerCase().includes(keyword) ||
                news.author.toLowerCase().includes(keyword)
            );
        }

        currentPage = 1;
        renderTable();
        renderPagination();
    }
    function handleSearch1(){
        const keyword = $('#searchInput1').val().trim().toLowerCase();

        if (keyword === '') {
            filteredData1 = [...resourceData];
        } else {
                filteredData1 = resourceData.filter(resource =>
                resource.title.toLowerCase().includes(keyword) ||
                resource.category.toLowerCase().includes(keyword) ||
                resource.author.toLowerCase().includes(keyword)
            );
        }

        currentPage1 = 1;
        renderTable1();
        renderPagination1();
    }
    // 编辑新闻
    function editNews(id) {
        const item = newsData.find(item => item.newsId === id);
        if (!item) {
            alert('新闻未找到');
            return;
        }
        $('#editTitle').val(item.title);
        $('#editCategory').val(item.category);
        $('#editAuthor').val(item.author);
        $('#editContent').val(item.content);
        openModal(id);
    }

    // 删除新闻
    function deleteNews(id) {
        if (confirm('确定要删除这条新闻吗？')) {
            // 模拟删除操作 - 实际应用中应调用后端API
            $.ajax(
                {
                    type: "DELETE",
                    url: `/admin/news/${id}`,
                    success: function(response) {
                        if(response.code===200){
                            fetchNewsData();
                            alert('新闻已删除');
                        }else{
                            alert("删除新闻失败");
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('删除新闻失败:', error);
                        if (xhr.status===403) {
                            alert("权限不足")
                            window.location.href = "../home.html";
                        } else if (xhr.status===401) {
                            alert("登录状态已过期")
                            localStorage.clear();
                            window.location.href = "../login.html";
                        }
                    }
                }
            )

            newsData = newsData.filter(item => item.id !== id);
            filteredData = [...newsData];
            renderTable();
            renderPagination();
        }
    }

    // 辅助函数：格式化日期
    function formatDate(timestamp) {
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    }

    // 辅助函数：获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'published': '已发布',
            'draft': '草稿'
        };
        return statusMap[status] || status;
    }
// 获取元素
        const mask = document.querySelector('.mask');
        const modal = document.querySelector('.edit-modal');
        let itemId=null;
        // 打开编辑框（可传入默认值）
        function openModal(id=null) {
            if (id===null){
                $('#editTitle').val('');
                $('#editCategory').val('项目新闻');
                $('#editAuthor').val('');
                $('#editContent').val('');
            }else{
                console.log(id);
            }
            mask.style.display = "block";
            modal.style.display = "block";
            itemId = id;

        }

        // 关闭编辑框
        function closeModal() {
            mask.style.display = "none";
            modal.style.display = "none";
            fetchNewsData();
        }

        // 保存编辑内容
        function saveEdit() {
            const title=$('#editTitle')
            const category=$('#editCategory')
            const author=$('#editAuthor')
            const content=$('#editContent')
            //获取第一个DOM元素，files是DOM元素的属性
            const image=$('#editImage').get(0);

            const form = new FormData();
            form.append('title', title.val());
            form.append('category', category.val());
            form.append('author', author.val());
            form.append('content', content.val());
            if (image.files[0]) {
                form.append('file', image.files[0]);
            }
            if(itemId === null) {
                $.ajax({
                        url: "/admin/news",
                        method: "POST",
                        data: form,
                    // 【这两个选项对于使用 FormData 至关重要】
                    processData: false,   // 阻止 jQuery 将 data 转换为查询字符串
                    contentType: false,   // 阻止 jQuery 自动设置 Content-Type 头
                        timeout: 5000,
                        success: function(response) {
                            if(response.code===200){
                                console.log(response);
                                alert('添加成功')
                                fetchNewsData();
                            }else{
                                console.error("出现错误");
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error(error)
                            if (xhr.status===403) {
                                alert("权限不足")
                                window.location.href = "../home.html";
                            } else if (xhr.status===401) {
                                alert("登录状态已过期")
                                localStorage.clear();
                                window.location.href = "../login.html";
                            }
                        }
                    }
                )
            }else {
                //if (content&&title&&category&&author&&status) {
                if (content&&title&&category&&author) {
                    form.append('newsId',itemId);
                    $.ajax({
                        url: "/admin/news",
                        method: "PUT",
                        timeout: 5000,
                        data:form,
                        // 【这两个选项对于使用 FormData 至关重要】
                        processData: false,   // 阻止 jQuery 将 data 转换为查询字符串
                        contentType: false,   // 阻止 jQuery 自动设置 Content-Type 头
                        success: function(response) {
                            if(response.code===200){
                                console.log(response);
                                alert('修改成功')
                                fetchNewsData();
                            }else{
                                alert(response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error(error)
                            if (xhr.status===403) {
                                alert("权限不足")
                                window.location.href = "../home.html";
                            } else if (xhr.status===401) {
                                alert("登录状态已过期")
                                localStorage.clear();
                                window.location.href = "../login.html";
                            }
                        }
                        }
                    )
                    closeModal();
                } else {
                    alert("请输入编辑内容");
                }
                itemId=null;
                $('#editTitle').val("");
                $('#editCategory').val("项目新闻");
                $('#editAuthor').val("");
                $('#editContent').val("");


                }

           console.log($('#editImage').get(0).value);
            //清除文件

            $('#editImage').get(0).value='';
            closeModal();

        }


         // 文件上传
        $(()=>{const fileUpload = document.getElementById('file-upload');
        fileUpload.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
        if (!fileUpload.value) {
            alert("请选择文件");
        return;
    }
                let file = fileUpload.files[0];
                alert(`已选择文件：${file.name}`);

                let form = new FormData();
                form.append('file', file);
                $.ajax({
                    url: '/admin/resources',
                    type: 'POST',
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if(response.code===200){
                            alert('文件上传成功');
                            // 上传成功后刷新资源列表
                            fetchResourceData();
                        }else{
                            alert('文件上传失败，请稍后重试');
                        }
                        //清空
                        $('#file-upload').get(0).value='';
                    },
                    error: function(xhr, status, error) {
                        console.error('文件上传失败:', error);
                        if (xhr.status===403) {
                            alert("权限不足")
                            window.location.href = "../home.html";
                        } else if (xhr.status===401) {
                            alert("登录状态已过期")
                            localStorage.clear();
                            window.location.href = "../login.html";
                        }
                    }
                });
            }
        });
        })
        
        


        // 删除文件
        function deleteResource(id) {
            if (confirm('确定要删除该文件吗？删除后无法恢复！')) {
                $.ajax(
                    {
                        type: "DELETE",
                        url: `/admin/resources/${id}`,
                        timeout:5000,
                        success: function(response) {
                            if(response.code===200){
                                fetchResourceData();
                                alert('文件已删除');
                            }else{
                                alert("删除文件失败");
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('删除文件失败:', error);
                            if (xhr.status===403) {
                                alert("权限不足")
                                window.location.href = "../home.html";
                            } else if (xhr.status===401) {
                                alert("登录状态已过期")
                                localStorage.clear();
                                window.location.href = "../login.html";
                            }
                        }
                    }
                )
            }else{
                alert("出了点问题")
            }
            fetchResourceData();
        }
</script>
</body>
</html>